package com.jason.choosenamefx.controller;

import com.jason.choosenamefx.constant.DataBaseCons;
import com.jason.choosenamefx.dao.SqliteHelper;
import com.jason.choosenamefx.entity.RowMapper;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.*;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * mvc 业务逻辑控制器
 */
public class AppController implements Initializable {

    /**
     * 定时器循环调用
     */
    Timeline timeline;

    /**
     * 数据
     */
    List<String> namesList = new ArrayList<>();

    /**
     * 定时的时间间隔 毫秒级 100ms 每次 显示一次
     */
    private double INTERVAL_TIME = 50;

    /**
     * 定时器 计数器
     */
    private long lastTimerCall = 0;

    static String APP_ICO_PATH = "/img/icon/app_ico.png";
    static String EXIT_ICO_PATH = "/img/icon/quit_ico.png";
    static String SETTING_ICO_PATH = "/img/icon/setting_ico.png";
    static String START_BTN_ICO = "/img/icon/start_btn.png";
    static String END_BTN_ICO = "/img/icon/end_btn.png";
    static String ABOUT_ICO_PATH = "/img/icon/about_ico.png";
    static String VERSION_ICO_PATH = "/img/icon/version_ico.png";
    static String ABOUT_BG_PATH = "/img/about_bg.png";

    Image exit_icon;
    Image about_icon;
    Image setting_icon;
    Image version_icon;
    Image start_btn_icon;
    Image end_btn_icon;
    Image app_icon;
    Image about_bg_icon;

    /**
     * showNameId 显示选择后的姓名
     */
    @FXML
    private Label showNameId;

    /**
     * 显示当前时间
     */
    @FXML
    private Text showNowTimeId;


    /**
     * 开始选择按钮
     */
    @FXML
    private Button startChooseId;

    /**
     * 结束选择按钮
     */
    @FXML
    private Button endChooseId;

    /**
     * 初始化 加载数据 初始化 fxml的生命周期里就处理 开启时间显示
     * @param url
     * @param resourceBundle
     */
    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), event -> {
            LocalDateTime now = LocalDateTime.now();
            showNowTimeId.setText(formatter.format(now));
        }));
        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();
        // 初始化全局使用的app ico 图标
        app_icon = new Image(getClass().getResourceAsStream(APP_ICO_PATH));
        exit_icon = new Image(getClass().getResourceAsStream(EXIT_ICO_PATH));
        about_icon = new Image(getClass().getResourceAsStream(ABOUT_ICO_PATH));
        setting_icon = new Image(getClass().getResourceAsStream(SETTING_ICO_PATH));
        version_icon = new Image(getClass().getResourceAsStream(VERSION_ICO_PATH));
        about_bg_icon = new Image(getClass().getResourceAsStream(ABOUT_BG_PATH));



        System.out.print("== 开始初始化 initialize  初始化开始按钮图标 ==");
        start_btn_icon = new Image(getClass().getResourceAsStream(START_BTN_ICO));
        ImageView start_btn_iv = new ImageView(start_btn_icon);
        startChooseId.setGraphic(start_btn_iv);
        System.out.print("== 开始初始化 initialize  初始化结束按钮图标 ==");
        end_btn_icon = new Image(getClass().getResourceAsStream(END_BTN_ICO));
        ImageView end_btn_iv = new ImageView(end_btn_icon);
        endChooseId.setGraphic(end_btn_iv);

    }

    /**
     * onAboutFun 关于
     */
    @FXML
    protected void onAboutFun() {
        System.out.print("触发 onAboutFun");
        // 创建新的 stage
        Stage stage = new Stage();
        Label label = new Label("基于JavaFx的开源的随机点名程序，欢迎大家使用！");
        label.setStyle("-fx-font-size: 12px;-fx-text-fill: red;-fx-fit-to-width: 320;-fx-alignment: center;");
        HBox secondPane = new HBox(label);
        stage.setTitle("关于@Jason");
        stage.getIcons().add(about_icon);
        BackgroundImage bi =  new BackgroundImage(about_bg_icon, BackgroundRepeat.REPEAT,BackgroundRepeat.REPEAT,
                BackgroundPosition.CENTER,BackgroundSize.DEFAULT
        );
        secondPane.setBackground(new Background(bi));
        Scene secondScene = new Scene(secondPane, 320, 120);
        stage.setScene(secondScene);
        //禁止调整大小
        stage.setResizable(false);
        stage.show();
    }

    /**
     * onQuitFun 退出
     */
    @FXML
    protected void onQuitFun() {
        System.out.print("触发 onQuitFun");
        Stage stage = new Stage();
        Label label = new Label("确定要退出吗？");
        StackPane secondPane = new StackPane(label);
        stage.getIcons().add(exit_icon);
        stage.setTitle("退出");
        Scene secondScene = new Scene(secondPane, 300, 200);
        stage.setScene(secondScene);
        //禁止调整大小
        stage.setResizable(false);
        stage.show();
    }


    /**
     * onVersionFun
     */
    @FXML
    protected void onVersionFun() {
        System.out.println("==触发onVersionFun==");
        Stage stage = new Stage();
        Label label = new Label("当前版本V1.0");
        label.setStyle("-fx-text-fill: #002aff;");
        StackPane secondPane = new StackPane(label);
        stage.setTitle("版本2024@V1.0");
        stage.getIcons().add(version_icon);
        Scene secondScene = new Scene(secondPane, 280, 30);
        stage.setScene(secondScene);
        //禁止调整大小
        stage.setResizable(false);
        stage.show();
    }


    /**
     * onOpenFun
     */
    @FXML
    protected void onOpenFun() {
        System.out.println("==触发 onOpenFun==");
        Stage stage = new Stage();
        Label label = new Label("开源地址为：\n https://gitee.com/ucanner/choose-name-fx.git");
        label.setStyle("-fx-text-fill: #ff7302;");
        StackPane secondPane = new StackPane(label);
        stage.setTitle("欢迎@Star&Fork");
        stage.getIcons().add(app_icon);
        Scene secondScene = new Scene(secondPane, 280, 30);
        stage.setScene(secondScene);
        //禁止调整大小
        stage.setResizable(false);
        stage.show();
    }


    /**
     * onSetFun
     */
    @FXML
    protected void onSetFun() {
        System.out.println("==触发 onSetFun ==");
        Stage stage = new Stage();
        HBox root = new HBox();
        Label label = new Label("请上传规范数据,每行一个姓名。");
        Button fileBtn = new Button("上传txt数据");
        fileBtn.setLayoutX(50);
        fileBtn.setOnAction(action -> {
            //创建一个文件选择器
            FileChooser fc = new FileChooser();
            fc.setTitle("Please上传规范的数据");
            fc.getExtensionFilters( ).add(new FileChooser.ExtensionFilter("点名数据 (*.txt)", "*.txt"));
            File selectFile = fc.showOpenDialog(stage);
            ArrayList<String> namesLists = new ArrayList<>();
            if(null != selectFile){
                // 上传完成后弹出提示框
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("上传成功");
                alert.setHeaderText(null);
                alert.setContentText("文件上传成功！");
                alert.showAndWait();
                // 关闭窗口
                // stage.close();
                System.out.println("== 这里是数据处理逻辑，解析出来，存储到sql_lite ==");
                try {
                    Scanner scanner = new Scanner(selectFile);
                    while (scanner.hasNextLine()) {
                        String line = scanner.nextLine();
                        namesLists.add(line);
                        System.out.println(line);
                    }
                    scanner.close();
                    // 存入sql_lite 数据库
                    if (namesLists != null){
                        SqliteHelper dbHelper = new SqliteHelper(DataBaseCons.DB_NAME);
                        dbHelper.executeUpdate("drop table if exists "+DataBaseCons.DB_TABLE_NAME+";");
                        dbHelper.executeUpdate("create table "+DataBaseCons.DB_TABLE_NAME+"(id INTEGER PRIMARY KEY,name varchar(20));");
                        for (String name : namesLists) {
                            // 对元素进行操作
                            dbHelper.executeUpdate("insert into  "+DataBaseCons.DB_TABLE_NAME+"(name) values('"+name+"');");
                        }
                    }
                } catch (FileNotFoundException | ClassNotFoundException | SQLException e) {
                    e.printStackTrace();
                }

            }
        });
        root.getChildren().add(fileBtn);
        root.getChildren().add(label);
        stage.setTitle("软件设置");
        stage.getIcons().add(setting_icon);
        Scene secondScene = new Scene(root, 300, 30);
        stage.setScene(secondScene);
        //禁止调整大小
        stage.setResizable(false);
        stage.show();
    }

    /**
     * onStartChooseNameFun
     */
    @FXML
    protected void onStartChooseNameFun() {
        System.out.println("== 触发 onStartChooseNameFun ==");
        // 实现按钮 Start / 开始 切换 给出视觉交互
        if("Start".equalsIgnoreCase(startChooseId.getText())){
            startChooseId.setText("开始");
        }else {
            startChooseId.setText("Start");
        }

        /**
         * 核心业务逻辑 从excel 里面读取数据 存储到 缓存里面？（持久化）
         * 选择结构化 数据库 sql 还是 nosql?
         *
         */
        //1.数据库若有就不处理，若无就创建在项目的根目录，命名为xx.db
        //2.将数据设置进去 数据结构为  序号id    姓名
        //3.id随机生成   班级若无就每次生成一个随机数来代表 （后期优化添加字段） 姓名
        //4.excel读取数据（后面来做）（简单版可以从txt里面读取）
        //5.按照循序读取 去重 然后随机取出
        try{
            SqliteHelper dbHelper = new SqliteHelper(DataBaseCons.DB_NAME);
             namesList = dbHelper.executeQuery("select name from "+DataBaseCons.DB_TABLE_NAME+";", new RowMapper<String>() {
                @Override
                public String mapRow(ResultSet rs, int index) throws SQLException {
                    System.out.println(rs.getString("name"));
                    return rs.getString("name");
                }

            });
        }catch(Exception e){
            System.out.println("==== 出现数据库异常 ====");
            e.printStackTrace();
        }
        int names_size = namesList.size();
        Random random = new Random();
        //防止重开线程
        if (timeline==null){
            timeline = new Timeline(new KeyFrame(
                    //定时间隔 毫秒级别
                    Duration.millis(INTERVAL_TIME),
                    ae -> {
                        lastTimerCall++;
                        //取出数据 循环显示到页面
                        if (namesList!=null & names_size!=0){
                            int randomNum = random.nextInt(names_size);
                            showNameId.setText(namesList.get(randomNum));
                        }
                    }
            ));
            timeline.setCycleCount(Timeline.INDEFINITE);
            timeline.play();
        }
    }

    /**
     * 完成初始化数据逻辑 没有就创建 【每次程序启动】+加入清除按键
     * @return
     */
    public int initDataBaseFun() throws SQLException, ClassNotFoundException {
        SqliteHelper h = new SqliteHelper(DataBaseCons.DB_NAME);
        Random random = new Random();
        int nnn = random.nextInt(100);
        // 如果没有就创建 names 表
        //h.executeUpdate("drop table if exists "+DataBaseCons.DB_TABLE_NAME+";");
        //h.executeUpdate("create table "+DataBaseCons.DB_TABLE_NAME+"(id INTEGER PRIMARY KEY,name varchar(20));");
        //h.executeUpdate("insert into test values('Sql_Lite_数据库测试_ByJason');");
        h.executeUpdate("insert into  "+DataBaseCons.DB_TABLE_NAME+"(name) values('ByJason');");
        List<String> sList = h.executeQuery("select name from "+DataBaseCons.DB_TABLE_NAME+";", new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet rs, int index) throws SQLException {
                System.out.println(rs.getString("name"));
                return rs.getString("name");
            }
        });
        return 0;
    }

    /**
     * onDataInFun 数据导入
     */
    @FXML
    protected void onDataInFun() {
        System.out.println("==触发 onDataInFun ==");

    }

    /**
     * onOpenUrlFun 打开开源地址
     */
    @FXML
    protected void onOpenUrlFun() {
        System.out.println("==触发 onOpenUrlFun ==");
    }

    /**
     * onEndChooseFun 点击结束
     */
    @FXML
    protected void onEndChooseFun() {
        System.out.println("==触发 onEndChooseFun ==");
        // 实现按钮 End / 结束 切换 给出视觉交互
        if("End".equalsIgnoreCase(endChooseId.getText())){
            endChooseId.setText("结束");
        }else {
            endChooseId.setText("End");
        }

        if(timeline!=null){
            timeline.stop();
            //设置为null 防止重开线程
            timeline = null;
        }
    }


}